// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var base = require("base");
	var databind = require("databind");
	var tools = require("tools");
	var ctx3 = document.getElementById('chart3').getContext('2d');
	var ctx2 = document.getElementById('chart2').getContext('2d');
	var ctx8 = document.getElementById('chart8').getContext('2d');3
	var currentData;
	var geoCoordMap;
	//	var _css = require("./login.css");

	var init = function() {
		initEvent();
	};
	
	var initEvent = function() {
		//前十大货品
		
		inquireRankingDatas(1, 1);
		inquireRankingDatas(2, 2);
		inqurieReceivePaymentDetail();
		inquireManagerBordDetail();
		inquireEnterpriseArea();
		inquireEnterpriseLocation();
		
		
//		setInterval(function(){
//			inquireRankingDatas(1, 1);
//			inquireRankingDatas(2, 2);
//			inqurieReceivePaymentDetail();
//			inquireManagerBordDetail();
//			inquireEnterpriseArea();
//		}, 30000);

		
	};
	
	var myChart8 = function(d1, d2, cr1, cr2) {
		new Chart(ctx8, {
		type: 'pie',
		data: {
			labels: d1,
			datasets: [{
				data: d2,
				backgroundColor: cr1,
				borderColor: cr2,
				borderWidth: '2',
				pointRadius: '10',
				hoverBorderWidth: '0',
				hoverBorderColor: ['#2185da', '#2185da', '#2185da'],
			}],
		},
		options: {
			legend: {
				position: 'bottom',
				display: true,
			},
		},
	});
	}
	
	var inquireEnterpriseArea = function(type, charNum) {
		base.fnAjax({
			action: "inquireEnterpriseArea.json",
			async: true,
			nocode: true,
			oData: {
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					var d1 = [];
					var d2 = [];
					$.each(data.datas, function() {
						var _this = this;
						d1.push(_this.name);
						d2.push(_this.value);
					});
					var cr1 = [];
					var cr2 = [];
//						getRandomColor
					for(var i = 0; i < d1.slice(0, 10).length; i++) {
						cr1.push(getRandomColor(0.5));
						cr2.push(getRandomColor(1));
					}
//					alert(d1);
//					alert(d2);
					myChart8(d1.slice(0, 10), d2.slice(0, 10), cr1, cr2);
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	var inquireManagerBordDetail = function() {
		base.fnAjax({
			action: "inquireManagerBordDetail.json",
			async: true,
			nocode: true,
			oData: {
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					//总金额
					$('.counter1').jOdometer({
						increment: 0,
						counterStart: data.datas[0].loanAmount, 
						easing:'linear',
						numbersImage: 'images/jodometer-numbers.png', 
					  	spaceNumbers: 1, 
					  	heightNumber: 64,
					  	widthNumber:40,
					  	spaceNumbers:10,
					  	formatNumber:true,
					}); 
					
					$(".data_1 p").html((data.datas[0].enterpriseCreditLine/10000).toFixed(2) + "万元");
					$(".data_1 .chart_10_title").html("直客额度");
					$(".data_2 p").html((data.datas[0].distributorsCreditLine/10000).toFixed(2) + "万元");
					$(".data_2 .chart_10_title").html("分销商额度");
					$(".data_3 p").html((data.datas[0].enterpriseCreditLineAlready/10000).toFixed(2) + "万元");
					$(".data_3 .chart_10_title").html("直客敞口额度");
					$(".data_4 p").html((data.datas[0].distributorsCreditLineAlready/10000).toFixed(2) + "万元");
					$(".data_4 .chart_10_title").html("分销商敞口额度");
					
					var func1 = function(){
						$(".data_1 p").html((data.datas[0].enterpriseCreditLine/10000).toFixed(2) + "万元");
						$(".data_1 .chart_10_title").html("直客额度");
						$(".data_2 p").html((data.datas[0].distributorsCreditLine/10000).toFixed(2) + "万元");
						$(".data_2 .chart_10_title").html("分销商额度");
						$(".data_3 p").html((data.datas[0].enterpriseCreditLineAlready/10000).toFixed(2) + "万元");
						$(".data_3 .chart_10_title").html("直客敞口额度");
						$(".data_4 p").html((data.datas[0].distributorsCreditLineAlready/10000).toFixed(2) + "万元");
						$(".data_4 .chart_10_title").html("分销商敞口额度");
					}
					
					var func2 = function(){
						$(".data_1 p").html((data.datas[0].loanAmount/10000).toFixed(2) + "万元");
						$(".data_1 .chart_10_title").html("累计放款金额");
						$(".data_2 p").html((data.datas[0].receiveAmount/10000).toFixed(2) + "万元");
						$(".data_2 .chart_10_title").html("累计还款金额");
						$(".data_3 p").html((data.datas[0].currentLoanAmount/10000).toFixed(2) + "万元");
						$(".data_3 .chart_10_title").html("本月放款金额");
						$(".data_4 p").html((data.datas[0].currentReceiveAmount/10000).toFixed(2) + "万元");
						$(".data_4 .chart_10_title").html("本月还款金额");
					}
					
					var i = 0;
					setInterval(function(){
						if (i % 2 == 0) {
							func1();
						} else {
							func2();
						}
						i++;
					}, 3000);
					
//					String str = "" +
//					"直客授信额度（万元）:" + data.datas[0]. +
//					"分销商授信额度（万元）:" + data.datas[0]. +
//					"直客敞口额度（万元）:" + data.datas[0]. +
//					"分销商敞口额度（万元）:" + data.datas[0]. +
//					"累计放款金额（万元）:" + data.datas[0]. +
//					"累计还款金额（万元）:" + data.datas[0]. +
//					"本月放款金额（万元）:" + data.datas[0]. +
//					"本月还款金额（万元）:" + data.datas[0]. +
//					"今日放款金额（万元）:" + data.datas[0]. +
//					"今日还款金额（万元）:" + data.datas[0]. +
//					"资金余额（万元）:" + data.datas[0]. +
//					"累计实收利息（万元）:"  data.datas[0]. +;
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	var myChart3 = function(d1, d2, cr1, cr2){
		console.log(d1);
		console.log(d2);
		var c3 = new Chart(ctx3, {
			type: 'horizontalBar',
			data: {
//				labels: ["上海", "广州", "泉州", "海口", "青岛", "天津"],
				labels: d1,
				datasets: [{
					label: "前十大货品分析",
					borderWidth: '2',
					backgroundColor: cr1,
					borderColor: cr2,
					pointBackgroundColor: "#46ffc3",
					pointStrokeColor: "#fff",
					data: d2
				}]
			},
			options: {
				maintainAspectRatio: false,
				legend: {
					labels: {
						//	    			defaultFontColor: '#ffffff',
						//		            fontColor: '#ffffff',
					},
					display: false,
				},
			},
		});
	}

	var inquireRankingDatas = function(type, charNum) {
		base.fnAjax({
			action: "inquireRankingDatas.json",
			async: true,
			nocode: true,
			oData: {
				type: type
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
//					data1 = data.datas;
					var d1 = [];
					var d2 = [];
					$.each(data.datas, function() {
						var _this = this;
						d1.push(_this.name);
						d2.push(_this.value);
					});
					if (charNum == 1) {
						var cr1 = [];
						var cr2 = [];
//						getRandomColor
						for(var i = 0; i < d1.slice(0, 10).length; i++) {
							cr1.push(getRandomColor(0.5));
							cr2.push(getRandomColor(1));
						}
						myChart3(d1.slice(0, 10), d2.slice(0, 10), cr1, cr2);
					} else if (charNum == 2) {
						$("#toptenlicon").html("");
						for(var i = 0; i < d1.slice(0, 10).length; i++) {
							var str = '<li><p class="status" style="width:50%">'+d1.slice(0, 10)[i]+'</p><p class="amount" style="width:auto"></p><p style="width:auto" class="time"></p><p class="area" style="width:25%">&#65509;'+tools.formatCurrency(d2.slice(0, 10)[i])+'</p>';
							$("#toptenlicon").append(str);
							var box2=document.getElementById("toptenlibox");
							var con2=document.getElementById("toptenlicon");
							 
							var speed2=500;
							if(con2.offsetHeight>box2.offsetHeight){
								con2.innerHTML+=con2.innerHTML;
							}
							var times2=setInterval(scrollUp2,speed2);
							function scrollUp2(){
								if (box2.scrollTop>=con2.scrollHeight/2) {
									box2.scrollTop=0;
								} else{
									box2.scrollTop++;
								}
							}
							box2.onmouseover=function(){
								clearInterval(times2);
							}
							box2.onmouseout=function(){
								times2=setInterval(scrollUp2,speed2);
							}
						}
					}
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	
	var inqurieReceivePaymentDetail = function() {
		base.fnAjax({
			action: "inqurieReceivePaymentDetail.json",
			async: true,
			nocode: true,
			oData: {
				type: 1
			}, //传递参数
			fnSuccess: function(data) {
					var datas1 = data.datas[0].dates;
					var datas2 = data.datas[0].receives;
					var datas3 = data.datas[0].payments;
					myChart2(datas1, datas2, datas3);
				if(data.status == 200) {
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	function randomValue() {
	    return Math.round(Math.random()*100);
	};
	
	//企业城市经纬度信息
	var inquireEnterpriseLocation = function() {
		base.fnAjax({
			action: "inquireEnterpriseLocation.json",
			async: true,
			nocode: true,
			oData: {
				type: 1
			}, //传递参数
			fnSuccess: function(data) {
					currentData = data.datas[0].currentData;
					geoCoordMap = data.datas[0].geoCoordMap;
					showArea();
				if(data.status == 200) {
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	var showArea = function (){
		var convertData = function (data) {
		    var res = [];
		    for (var i = 0; i < data.length; i++) {
		        var geoCoord = geoCoordMap[data[i].name];
		        if (geoCoord) {
		            res.push({
		                name: data[i].name,
		                value: geoCoord.concat(data[i].value)
		            });
		        }
		    }
		    return res;
		};
		
		option = {
		    backgroundColor: 'none',
		    title: {
		        x:'center',
		        textStyle: {
		            color: '#fff'
		        }
		    },
		    tooltip: {
		        trigger: 'item',
		        formatter: function (params) {
		            return params.name + ' : ' + params.value[2];
		        }
		    },
		    legend: {
		        
		    },
		    visualMap: {
		        min: 0,
		        max: 100000000,
		        calculable: true,
		//      orient: 'horizontal',
		//      align: 'top',
		        top:'50%',
		        left: '2%',
		        inRange: {
		            color: ['rgba(0,110,221,1)','rgba(255,241,168,1)','rgba(255,105,105,1)']
		        },
		        textStyle: {
		            color: '#fff'
		        }
		    },
		    geo: {
		    	type: 'map',
		        map: 'china',
		        geoIndex: 0,
		        roam:true,
		        zoom:1.2,
		        left:'14%',
		        label: {
		            emphasis: {
		                show: true
		            }
		        },
		        itemStyle: {
		            normal: {
		                areaColor: 'rgba(34, 88, 145,.9)',
		                borderColor: '#aaa'
		            },
		            emphasis: {
		                areaColor: '#2a333d'
		            }
		        }
		    },
		    series: [
		    	{
		            name: 'points',
		            type: 'scatter',
		            coordinateSystem: 'geo',
		            data: convertData(currentData),
		            symbolSize: 25,
		            label: {
		                normal: {
		                    show: false
		                },
		                emphasis: {
		                    show: false
		                }
		            },
		            itemStyle: {
		                emphasis: {
		                    borderColor: '#fff',
		                    borderWidth: 1
		                }
		            }
		        }
		    ]
		};
		if (option && typeof option === "object") {
		    myChart.setOption(option, true);
		}
	}
	
	
	var myChart2 = function(datas, payments, receives){
		var c2 = new Chart(ctx2, {
			type: 'line',
			data: {
//				labels: ["一月", "二月", "三月", "四月", "五月", "六月", "七月"],
				labels: datas,
				datasets: [{
						label: "放款",
						borderWidth: '3',
						backgroundColor: "rgba(94,151,200,0.5)",
						borderColor: "rgba(94,151,200,1)",
						pointBackgroundColor: "#46ffc3",
						pointStrokeColor: "#fff",
						data: payments
					},
					{
						label: "回款",
						borderWidth: '3',
						backgroundColor: "rgba(212,228,249,0.5)",
						borderColor: "rgba(212,228,249,1)",
						pointBackgroundColor: "#46ffc3",
						pointStrokeColor: "#fff",
						data: receives
					}
				]
			},
			options: {
				legend: {
					labels: {
						//	    			defaultFontColor: '#ffffff',
						//		            fontColor: '#ffffff',
					},
					//	            display: false,
				},
			},
		});
	}
	

	var inquireEnterpriseFinanceSummaryPageList = function() {
		//loading层
		base.fnAjax({
			action: "inquireEnterpriseFinanceSummaryPageList.json",
			async: true,
			nocode: true,
			oData: {
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					juicer.register("formatCurrency", tools.formatCurrency);
					var tpl = $(".summaryTpl").html();
					var html = juicer(tpl, data);
					$(".summaryTab tbody").html(html);
					$('.summaryTab').stickySort({ 
						sortable: true
					});
					layer.close(ii);
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	var testSummayry = function() {
		base.fnAjax({
			action: "testSummayry.json",
			async: true,
			oData: {
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
				} else { 
					layer.msg(data.message);
				}
			}
		});
	};
	
	var showChart1 = function(d, d1) {
		// 基于准备好的dom，初始化echarts实例
		var myChart1 = echarts.init(document.getElementById('main1'));
		// 指定图表的配置项和数据
		//app.title = '嵌套环形图';

		var option = {
			title: {
				text: '',
				subtext: '一润供应链',
				x: 'left'
			},
			tooltip: {
				trigger: 'item',
				formatter: "{a} <br/>{b} : {c} ({d}%)"
			},
			legend: {
				 orient: 'horizontal',
		         x: 'left',
		         y:'bottom',		
		        data:d1
		    },
			toolbox: {
				show: true,
				feature: {
					mark: {
						show: true
					},
					dataView: {
						show: true,
						readOnly: false
					},
					magicType: {
						show: true,
						type: ['pie', 'funnel']
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true
					}
				}
			},
			calculable: true,
			series: [{
				name: '访问来源',
				type: 'pie',
				radius: ['30%', '50%'],
				avoidLabelOverlap: false,
				center: ['50%', '60%'],
				data: d,
				itemStyle: {
					emphasis: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}]
		};

		// 使用刚指定的配置项和数据显示图表。
		myChart1.setOption(option);
		// 处理点击事件并且跳转到相应的百度搜索页面
		myChart1.on('click', function(params) {
			//window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name));
			window.open('../rankingDetail/rankingDetail.html?goodsName=' + encodeURI(encodeURI(params.name)) + '&bulkstockInfoId=' + params.data.detailId);
		});
	};

	var showChart2 = function(d, d1) {
		// 基于准备好的dom，初始化echarts实例
		var myChart2 = echarts.init(document.getElementById('main0'));
		// 指定图表的配置项和数据
		//app.title = '嵌套环形图';

		var option = {
			title: {
				text: '',
				subtext: '一润供应链',
				x: 'left'
			},
			tooltip: {
				trigger: 'item',
				formatter: "{a} <br/>{b} : {c} ({d}%)"
			},

			toolbox: {
				show: true,
				feature: {
					mark: {
						show: true
					},
					dataView: {
						show: true,
						readOnly: false
					},
					magicType: {
						show: true,
						type: ['pie', 'funnel']
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true
					}
				}
			},
			legend: {
				 orient: 'horizontal',
		         x: 'left',
		         y:'bottom',		
		        data:d1
		    },
			calculable: true,
			series: [{
				name: '融资金额',
				type: 'pie',
				radius: ['30%', '50%'],
				avoidLabelOverlap: false,
				center: ['50%', '60%'],
				data: d,
				itemStyle: {
					emphasis: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}]
		};

		// 使用刚指定的配置项和数据显示图表。
		myChart2.setOption(option);
		// 处理点击事件并且跳转到相应的百度搜索页面
		myChart2.on('click', function(params) {
			//window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name));
			window.open('../rankingDetail/rankingDetail1.html?customerName=' + encodeURI(encodeURI(params.name)) + '&enterpriseId=' + params.data.detailId);
		});
	};

	var showChart3 = function() {
		// 基于准备好的dom，初始化echarts实例
		var myChart2 = echarts.init(document.getElementById('main2'));

		// 指定图表的配置项和数据
		//app.title = '嵌套环形图';

		var option = {
			color: ['#3398DB'],
			title: {
				text: '客户违约排行',
				subtext: '一润供应链'
			},
			tooltip: {
				trigger: 'axis'
			},
			legend: {
				data: ['违约']
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: { // 坐标轴指示器，坐标轴触发有效
					type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
				}
			},
			grid: {
				left: '3%',
				right: '4%',
				bottom: '3%',
				containLabel: true
			},
			toolbox: {
				show: true,
				feature: {
					dataView: {
						show: true,
						readOnly: false
					},
					magicType: {
						show: true,
						type: ['line', 'bar']
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true
					}
				}
			},
			calculable: true,
			xAxis: [{
				type: 'category',
				data: ['浙江永福', '福建鑫泰', '江苏有限', '上海永新', '南京化工', '广州南方', '海南永康', '天津豪迈'],
				axisTick: {
					alignWithLabel: true
				}
			}],
			yAxis: [{
				type: 'value'
			}],
			series: [{
				name: '收款',
				type: 'bar',
				barWidth: '60%',
				label: {
					normal: {
						show: true,
						position: 'inside'
					}
				},
				data: [0, 0, 0, 0, ,0, 0, 0, 0]
			}]
		};

		// 使用刚指定的配置项和数据显示图表。
		myChart2.setOption(option);
	}
	
	var getRandomColor = function(l) {
		var w = 255;
		Math.random()*255
		var color = "rgba("+parseInt(Math.random()*255, 10)+","+parseInt(Math.random()*255, 10)+","+parseInt(Math.random()*255, 10)+","+l+")";
		return color;
	}

	return {
		init: init
	};
});